<!--
 * @Author: sansuixiaoxianxian 1634119605@qq.com
 * @Date: 2025-07-09 10:15:21
 * @LastEditors: sansuixiaoxianxian 1634119605@qq.com
 * @LastEditTime: 2025-07-11 17:28:33
 * @FilePath: /travel-record-library/src/pages/SystemDataManagement/SystemDataManagement.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<Page title="系统数据管理" class="data-management-page">
		<template #body>
			<!-- 操作工具栏 -->
			<div class="action-toolbar">
				<van-checkbox v-model="main.isCheckAll" :indeterminate="main.isIndeterminate" @change="checkAllChange">
					全选
				</van-checkbox>

				<div class="action-buttons">
					<van-button type="success" class="action-btn" @click="exportData">
						<i class="fas fa-upload"></i>
						导出
					</van-button>

					<van-uploader accept=".txt, text/plain" max-count="1" :after-read="importData">
						<van-button type="primary" class="action-btn">
							<i class="fas fa-download"></i>
							导入
						</van-button>
					</van-uploader>

					<van-button type="danger" class="action-btn" @click="clearDatabase">
						<i class="fas fa-trash-alt"></i>
						清空
					</van-button>
				</div>
			</div>

			<van-dialog v-model:show="main.showExportExcelDialog" title="出差记录库导出" show-cancel-button
				@confirm="handleExportConfirm">
				<div class="export-dialog-content">
					<van-radio-group v-model="exportFormat">
						<van-cell-group>
							<van-cell title="导出为Excel文件(.csv)" clickable @click="exportFormat = 'excel'">
								<template #right-icon>
									<van-radio name="excel" />
								</template>
							</van-cell>
							<van-cell title="导出为文本文件(.txt)" clickable @click="exportFormat = 'text'">
								<template #right-icon>
									<van-radio name="text" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
				</div>
			</van-dialog>


			<!-- 数据列表 -->
			<div class="data-list">
				<van-checkbox-group v-model="main.selectProject" @change="checkedResultChange">
					<van-cell v-for="(item, index) in menuList" :key="item.library" :title="item.title" clickable
						@click="toggle(index)">
						<template #right-icon>
							<van-checkbox :name="item.library" ref="checkboxRefs" @click.stop />
						</template>
					</van-cell>
				</van-checkbox-group>
			</div>

			<!-- 路径提示 -->
			<div class="path-tip" v-if="main.downloadInfoTip">
				<template v-for="(segment, index) in pathSegments()" :key="index">
					<span v-if="segment.showFarstSlash" class="slash">/</span>
					<span class="path-segment">
						{{ segment.text }}
					</span>
					<span v-if="segment.showlastSlash" class="slash">/</span>
				</template>
			</div>
		</template>
	</Page>
</template>

<script setup lang="ts" name="SystemDataManagement">
import { reactive, ref } from "vue"
import SystemDataManagementClass, { menuList } from "./SystemDataManagement"
import { CheckboxInstance, UploaderAfterRead } from "vant"

import importDataUtil from "./importDataUtil.ts"
import exportDataUtil, { exportTravelInfos } from "./exportDataUtil.ts"
import clearDatabaseUtil from "./clearDatabaseUtil.ts"
import { DB, travelRecordLibraryKey } from "@/assets/global.ts"
import { FileExporter } from "@/utility/fileUtils.ts"
import { TTravelInfo } from "../AddTravelRecord/AddTravelRecord.ts"
import * as indexedDB from "@utility/indexedDB"

const main = reactive(new SystemDataManagementClass())

const exportFormat = ref<'excel' | 'text'>('excel')
// 导出确认处理
const handleExportConfirm = async () => {
	if (exportFormat.value == 'excel') {
		const result = (await indexedDB.queryAll(
			DB.store.TravelRecord.name
		)) as TTravelInfo[]
		const finalResult = exportTravelInfos(result).map(item => ({
			...item,
			travelPeople: item.travelPeople.map(it => (`${it.name}(${it.myTravelExpenses})`)).join(',')
		}))

		FileExporter.exportExcel(finalResult, {
			filename: main.selectProject.at(0),
			header: {
				// 编号
				id: "编号",
				// 出差日期
				travelDate: "出差日期",
				// 出差地址
				travelAddress: "出差地址",
				// 出差人员
				travelPeople: "出差人员",
				// 是否派车
				officialCars: "是否派车",
				// 出差事由
				travelReason: "出差事由",
				// 是否核销
				isReimbursed: "是否核销",
				// 出差费用
				travelExpenses: "出差费用",
				// 经办人员
				handledBy: "经办人员",
				// 备注
				notes: "备注",
				// 创建日期时间
				createDate: "创建日期时间",
			},
			dateFormat: 'YYYY/MM/DD HH:mm:ss'
		})
	} else {
		// 仅导出出差记录库且为TEXT类型时，执行此步骤
		const path = await exportDataUtil(main)
		main.downloadInfoTip = path
	}
}

const pathSegments = () => {
	const segments = main.downloadInfoTip.split("/").filter(Boolean)
	return segments.map((item, index) => ({
		text: item,
		// 不显示最后一个/
		showlastSlash: index < segments.length - 1,
		// 显示第一个/
		showFarstSlash: index == 0,
	}))
}

const importData: UploaderAfterRead = (file, datail) =>
	importDataUtil(file, datail)

const exportData = async () => {
	if (main.selectProject.length == 1 && main.selectProject.at(0) == travelRecordLibraryKey) {
		main.showExportExcelDialog = true
		return
	}
	const path = await exportDataUtil(main)
	main.downloadInfoTip = path
}

const clearDatabase = () => clearDatabaseUtil(main)

const checkedResultChange = (value: string[]) => {
	const checkCount = value.length
	main.isCheckAll = menuList.length == checkCount
	main.isIndeterminate = checkCount > 0 && checkCount < menuList.length
}

const checkAllChange = (bool: boolean) => {
	main.selectProject = bool ? menuList.map(it => it.library) : []
	main.isIndeterminate = false
}

const checkboxRefs = ref<CheckboxInstance[]>([])
const toggle = (index: number) => {
	checkboxRefs.value[index].toggle()
}
</script>

<style scoped lang="scss">
.action-toolbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 12px;
	background-color: white;
	border-radius: 8px;
	margin: 12px 0;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

	.action-buttons {
		display: flex;
		gap: 8px;
	}
}

.action-btn {
	min-width: 80px;
	height: 36px;
	font-size: 14px;
	border-radius: 6px;

	i {
		margin-right: 4px;
	}
}

.data-list {
	flex: 1;
	overflow-y: auto;
	background-color: white;
	border-radius: 8px;
	padding: 8px 0;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

	.van-cell {
		padding: 12px 16px;
	}
}

.path-tip {
	margin-top: 12px;
	padding: 10px;
	background-color: white;
	border-radius: 8px;
	font-size: 14px;
	white-space: nowrap;
	overflow-x: auto;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

	.path-segment {
		color: white;
		background-color: #07c160;
		padding: 4px 8px;
		border-radius: 16px;
		margin: 0 2px;
	}

	.slash {
		font-weight: bold;
		color: #969799;
	}
}
</style>